package com.mbc.common.manager;

import java.util.Date;
import java.util.List;

import javax.persistence.NoResultException;

import com.mbc.common.CommonConstants;
import com.mbc.common.data.MobileUserData;
import com.mbc.common.data.UserData;
import com.mbc.common.entities.ApplicationItem;
import com.mbc.common.entities.Branch;
import com.mbc.common.entities.SystemProperty;
import com.mbc.common.entities.User;
import com.mbc.common.entities.UserInBranches;
import com.mbc.common.exception.DataNotFoundException;
import com.mbc.common.exception.UnauthorizedAccessException;

public class SystemMgr extends AbstractMgr {
	
	public SystemMgr()
	{
		
	}
	
	public SystemMgr(String sessionId)
	{
		this.sessionId = sessionId;
	}
	
	public List<ApplicationItem> getAllAppItem()throws Exception{
		openConnection();
		try {
			return entityManager.createNamedQuery("ApplicationItem.findAll", ApplicationItem.class).getResultList();
		} catch (Exception e) {
			throw e;
		}
		finally{
			closeConnection();
		}
	}
	
	public MobileUserData mobileLogin(String loginId,String password)throws Exception{
		MobileUserData l_userData = new MobileUserData();
		openConnection();
		try {
			User l_user = null; 
			try {
				l_user = entityManager.createNamedQuery("User.findByLoginId",User.class)
				.setParameter("loginId", loginId)
				.getSingleResult();
			} catch (NoResultException innerEx) {
				throw new DataNotFoundException("Mobile => No user with LoginId \"" + loginId + "\"");
			}
			if(l_user != null){
				if(l_user.getPassword().equals(password)){
					if(l_user.getStatus() == CommonConstants.RecordStatus.delete)
						throw new UnauthorizedAccessException("User was deactivated.");
					
					UserInBranches l_ub = entityManager.createNamedQuery("UserInBranches.findByUserId", UserInBranches.class)
							.setParameter("userId", l_user.getUserId())
							.getSingleResult();
					
					Branch l_Branch = entityManager.find(Branch.class, l_ub.getBranchId()); // l_OfficeDAO.findByUserId(l_user.getUserId());
					
					l_userData.setName(l_user.getUserName());
					l_userData.setBranchId(l_Branch.getBranchId());
					l_userData.setBranchName(l_Branch.getName());
					l_userData.setUserId(l_user.getUserId());
				}
				else
					throw new UnauthorizedAccessException("Invalid password.");
			}
			else
				throw new UnauthorizedAccessException("Invalid Login Id.");
		}
		catch (Exception e) {
			throw e;
		}
		finally{
			closeConnection();
		}
		
		return l_userData;
	}
	
	public UserData login(String loginId, String password) throws Exception
	{
		UserData l_userData= new UserData();
		openConnection();
		try {
			User l_user = null; 
			try {
				l_user = entityManager.createNamedQuery("User.findByLoginId",User.class)
				.setParameter("loginId", loginId)
				.getSingleResult();
			} catch (NoResultException innerEx) {
				
			}
			if(l_user != null){
				if(l_user.getPassword().equals(password)){
					if(l_user.getStatus() == CommonConstants.RecordStatus.delete)
						throw new UnauthorizedAccessException("User was deactivated.");
//					if(l_user.getStatus() == UserMgr.USER_ONLINE)
//						throw new LockedUserException("User " + loginId + " is locked.");
					
					UserInBranches l_ub = entityManager.createNamedQuery("UserInBranches.findByUserId", UserInBranches.class)
							.setParameter("userId", l_user.getUserId())
							.getSingleResult();
					
					Branch l_Branch = entityManager.find(Branch.class, l_ub.getBranchId()); // l_OfficeDAO.findByUserId(l_user.getUserId());
					
					@SuppressWarnings("unchecked")
					List<ApplicationItem> l_appItemList = entityManager.createNamedStoredProcedureQuery("ApplicationItem.findByUserId")
								.setParameter("userId", l_user.getUserId())
								.getResultList();
					
					l_userData.setLoginID(l_user.getLoginId());
					l_userData.setUserName(l_user.getUserName());
					l_userData.setUserID(l_user.getUserId());
					l_userData.setBranchCode(l_Branch.getBranchCode());
					l_userData.setBranchId(l_Branch.getBranchId());
					l_userData.setBranchName(l_Branch.getName());
					l_userData.setCountryCode(l_Branch.getCountry());
					l_userData.setAppItemList(l_appItemList);
					l_user.setStatus(UserMgr.USER_ONLINE);
				}
				else
					throw new UnauthorizedAccessException("Invalid password.");
			}
			else
				throw new UnauthorizedAccessException("Invalid Login Id.");
		}
		catch (Exception e) {
			throw e;
		}
		finally{
			closeConnection();
		}
		return l_userData;
	}
	
	public SystemProperty getSystemProperty(String key)throws Exception{
		openConnection();
		try {
			return entityManager.find(SystemProperty.class, key);
		} catch (Exception e) {
			throw e;
		} finally {
			closeConnection();
		}
	}
	
	public void updateLatestLoginDateTime(Date latestLoginDateTime, long userId)throws Exception{
		openConnection();
		try {
			beginTransaction();
			User l_user = entityManager.find(User.class, userId);
			l_user.setLatestLoginDateTime(latestLoginDateTime);
			entityManager.merge(l_user);
			commitTransaction();
		} catch (Exception e) {
			rollbackTransaction();
			throw e;
		} finally {
			closeConnection();
		}
	}
}
